package flyingpig.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;

import com.thoughtworks.xstream.XStream;

import flyingpig.data.dao.ImageInfoHome;
import flyingpig.data.dao.JobPageHome;
import flyingpig.data.dao.SearchJobHome;
import flyingpig.data.domain.ImageInfo;
import flyingpig.data.domain.JobPage;
import flyingpig.data.domain.SearchJob;
import flyingpig.hibernate.HibernateUtil;

public class UploadImageInfos extends HttpServlet {

	private static Log logger = LogFactory.getLog(UploadImageInfos.class);
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadImageInfos() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        logger.info("批量上传开始");
        PrintWriter out = response.getWriter();
        
        // 用来统计每个pageId  finish了多少imageinfo
        int count = 0;
        int pageId = 0;
        String xmls = request.getParameter("xmls");
        logger.info("开始解析xml");
        String[] ii_xmls = xmls.split("<Seperator/>");
        XStream ox = new XStream();
        ox.alias("ImageInfo", ImageInfo.class);
        
        List<ImageInfo> ii_list = new ArrayList<ImageInfo>();
        for (String xml : ii_xmls) {
			if (!xml.trim().equals("")) {
				ImageInfo ii = (ImageInfo) ox.fromXML(xml);
				if (ii.getTags().length() > 1024) {
					ii.setTags(ii.getTags().substring(0, 1023));
				}
				ii.setLastUpdate(new Date());
				ii.setImageId(null);
				ii.setCacheState("UNCACHED");
				ii_list.add(ii);
			}
        }
        logger.info("解析得到所有ImageInfo 数量:" + ii_list.size());
		pageId = ii_list.get(0).getPageId();

		Transaction tx = HibernateUtil.getCurrentSession().beginTransaction();
		try {
			logger.info("开始persist");
			for (ImageInfo imageInfo : ii_list) {

				// 有没有相同的image存在
				ImageInfoHome imageInfoHome = new ImageInfoHome();
				List results = imageInfoHome.findByURL(imageInfo.getUrl());
				if (results.size() > 0) {
					ImageInfo xx = (ImageInfo) results.get(0);
					logger.info("冲突   imageInfo existed  ||| this pageId:"
							+ imageInfo.getPageId() + " conflict with pageId:"
							+ xx.getPageId());					
				} else {
					imageInfoHome.persist(imageInfo);
					count++;
				}
			}
			logger.info("persist完成，开始设置jobPage, 和searchJobPage");

			// 增长 JobPage finished num
			if (!setfinishedNum(pageId, count)) {
				tx.rollback();
			}
			tx.commit();

		} catch (HibernateException e) {

			logger.info("rollback");
			tx.rollback();
			e.printStackTrace();
			out.println("-1");
			out.flush();
			out.close();
			return;
		}	

		out.println(count);
		logger.info("批量上传结束，数量: " + count);
		out.flush();
		out.close();

	}
    
    private boolean setfinishedNum(int pageId, int count){   
    	
		JobPageHome jobPageHome = new JobPageHome();
		JobPage page = jobPageHome.findById(pageId);
		if (page == null) {
			logger.info("page wrong");
			return false;
		}
		page.setFinishedNum(page.getFinishedNum() + count);
		page.setLastUpdate(new Date());
		page.setPageState("COMPLETE");
		jobPageHome.persist(page);
		logger.info("searchJobID:" + page.getSearchJobId() + " | page:"
				+ page.getId() + " | finishedNum:" + page.getFinishedNum());
		addSearchJobFinishedNum(page);

		return true;
    }
    
    synchronized void addSearchJobFinishedNum(JobPage page){
		SearchJobHome searchJobDao = new SearchJobHome();
		SearchJob searchJob = searchJobDao.findById(page.getSearchJobId());
		searchJob.setFinishedNum(searchJob.getFinishedNum() + 1);
    }

}
